# coding=utf-8
import datetime
import logging.config
import logging as logger
import math
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LOG_DIR = os.path.join(BASE_DIR, "logs")
if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)  # 创建路径


def get_file_name_by_time():
    """
    15 分钟重置一次日志文件名
    :return: file_name
    """
    now = datetime.datetime.now()
    step = math.floor(now.minute / 15)
    minutes = 15 * step
    return now.strftime("%Y-%m-%d#%H{minutes}00".format(minutes=minutes)) + ".log"


def get_log_conf():
    return {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "simple": {
                'format': '%(asctime)s [%(name)s:%(lineno)d] [%(levelname)s]- %(message)s'
            },
            'standard': {
                'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(levelname)s]- %(message)s'
            },
        },

        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "level": "DEBUG",
                "formatter": "simple",
                "stream": "ext://sys.stdout"
            },

            "default": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "INFO",
                "formatter": "simple",
                "filename": os.path.join(LOG_DIR, get_file_name_by_time()),
                'mode': 'w+',
                "maxBytes": 1024 * 1024 * 5,  # 5 MB
                "backupCount": 20,
                "encoding": "utf8"
            },
        },

        "root": {
            'handlers': ['console', 'default'],
            'level': "INFO",
            'propagate': False
        }
    }


logging.config.dictConfig(get_log_conf())
